package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.FieldConfig;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.FieldConfigMapper;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.model.mapper.SuprAuthMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.core.RegionalCovert;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.KMAPI;
import com.ruoyi.system.outto.game.LCAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class KMAPIImpl implements KMAPI {

    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private SuprAuthMapper suprAuthMapper;
    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;
    private SalePartner salePartner;
    @Resource
    private FieldConfigMapper fieldConfigMapper;

    @Override
    public AjaxResult addGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(accountInfo, "1");
        log.info("酷猫添加接口请求参数={}", JSONObject.toJSONString(params));
        String threeOther = salePartner.getThreeOther();
        String response = "";
        String path = "/foreigndata/xiaotao/addgoods";
        if (StringUtils.isNotEmpty(threeOther)) {
            response = HttpUtils.sendPost(threeOther + path, JSONObject.toJSONString(params), "application/json");
        }


        log.info("酷猫添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"1".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(accountInfo, "1");
        String path = "/foreigndata/xiaotao/editgoods";
        log.info("酷猫编辑接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.sendPost(salePartner.getThreeOther() + path, JSONObject.toJSONString(params), "application/json");
        log.info("酷猫编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);

        if (!"1".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }


    private Map<String, Object> params(AccountInfo accountInfo, String type) {

        BigDecimal multiply = new BigDecimal(95);
        BigDecimal riseS = multiply.divide(new BigDecimal(100), 2, BigDecimal.ROUND_UP);
        BigDecimal bigDecimalS = accountInfo.getPrice().multiply(riseS).setScale(0, BigDecimal.ROUND_FLOOR);
        accountInfo.setPrice(bigDecimalS);
        String twoOther = salePartner.getTwoOther();
        String other = salePartner.getOther();
        Map<String, Object> params = new HashMap<>();
        params.put("mobile", twoOther);
        params.put("shopid", accountInfo.getId());
        params.put("name", accountInfo.getType());
        params.put("plat", other);
        params.put("server", "");
        params.put("title", descTitle + "|" + accountInfo.getId() + accountInfo.getDes());
        params.put("price", accountInfo.getPrice());
        params.put("type", type);
        params.put("image", accountInfo.getTitleImg());
        params.put("area", accountInfo.getRegional());
        String[] tengxunList = {"王者荣耀", "王者荣耀","火影忍者"};
        if (Arrays.asList(tengxunList).contains(accountInfo.getType())) {
            if (Objects.equals("安卓WX", accountInfo.getRegional())) {
                params.put("plat", "安卓");
                params.put("operator", "微信");
            }
            if (Objects.equals("安卓Q", accountInfo.getRegional())) {
                params.put("plat", "安卓");
                params.put("operator", "QQ");
            }
            if (Objects.equals("苹果WX", accountInfo.getRegional())) {
                params.put("plat", "苹果");
                params.put("operator", "微信");
            }
            if (Objects.equals("苹果Q", accountInfo.getRegional())) {
                params.put("plat", "苹果");
                params.put("operator", "QQ");
            }
        }
        if (Objects.equals("原神", accountInfo.getType())) {
            params.put("plat", "双平台互通");
            params.put("operator", "游戏官方");
        }
        if (Objects.equals("永杰无间", accountInfo.getType())) {
            if (Objects.equals("网易", accountInfo.getRegional())) {
                params.put("area", "网易官方区");
                params.put("server", "网易官方区");
            }
            if (Objects.equals("Steam", accountInfo.getRegional())) {
                params.put("area", "steam");
                params.put("server", "steam");
            }
        }
        if (Objects.equals("CF端游", accountInfo.getType())) {
            params.put("area", accountInfo.getRegional());
        }
        if (Objects.equals("英雄联盟", accountInfo.getType())) {
            params.put("server", accountInfo.getRegional());
        }
        if (Objects.equals("光遇", accountInfo.getType())) {
            params.put("plat", "双平台互通");
            if (Objects.equals("安卓网易邮箱", accountInfo.getRegional())) {
                params.put("operator", "安卓官方");
            }
            if (Objects.equals("苹果网易邮箱", accountInfo.getRegional())) {
                params.put("operator", "苹果官方");
            }
            if (Objects.equals("华为渠道服", accountInfo.getRegional())) {
                params.put("operator", "华为");
            }
            if (Objects.equals("OPPO渠道服", accountInfo.getRegional())) {
                params.put("operator", "OPPO渠道服");
            }
            if (Objects.equals("小米渠道服", accountInfo.getRegional())) {
                params.put("operator", "小米");
            }
        }

        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        String imgs = "";
        if (!CollectionUtils.isEmpty(infoImgs)) {
            imgs = infoImgs.stream().map(i -> i.getImgUrl()).collect(Collectors.joining(","));
        } else {
            imgs = LCConstant.defaultImg;
        }
        params.put("images", imgs);

        System.out.println(twoOther + salePartner.getSaleKey());
        String sign = DigestUtils.md5Hex(twoOther + salePartner.getSaleKey());
        params.put("sign", sign);

        String attr = getAttr(accountInfo);
        params.put("sku", attr);

        return params;
    }


    @Override
    public AjaxResult delGame(AccountInfo accountInfo, Long userId, SalePartner sa) {

        salePartner = sa;

        Map<String, Object> result = new HashMap<>();
        String threeOther = sa.getThreeOther();
        Map<String, Object> params = params(accountInfo, "2");
        log.info("酷猫删除接口请求参数={}", JSONObject.toJSONString(params));
        String path = "/foreigndata/xiaotao/delgoods";
        String response = "";
        response = HttpUtils.sendPost(threeOther + path, JSONObject.toJSONString(params), "application/json");
        if (StringUtils.isEmpty(response)) {
            throw new GlobalException("请求接口失败");
        }
        log.info("酷猫添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"1".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }


    private String getAttr(AccountInfo accountInfo) {

        JSONObject jsonObject = new JSONObject();

        String type = accountInfo.getType();

        if (Objects.equals("王者荣耀", accountInfo.getType())) {

            jsonObject.put("皮肤数量", accountInfo.getSkins());
            jsonObject.put("英雄数量", accountInfo.getHeroes());
            jsonObject.put("账号来源", "自己购买");
            jsonObject.put("实名认证", accountInfo.getLevel());
            setConfig(accountInfo, jsonObject);
        } else if (Objects.equals("永劫无间", type)) {
            jsonObject.put("实名认证", accountInfo.getLevel());
            setConfig(accountInfo, jsonObject);
        } else if (Objects.equals("CF端游", type)) {
            jsonObject.put("实名认证", accountInfo.getLevel());
            setConfig(accountInfo, jsonObject);
        } else if (Objects.equals("和平精英", type)) {
            jsonObject.put("套装数量", accountInfo.getSkins());
            jsonObject.put("枪皮数量", accountInfo.getGuns());
            jsonObject.put("账号来源", "自己购买");
            jsonObject.put("实名认证", accountInfo.getLevel());
            setConfig(accountInfo, jsonObject);
        }
        return JSON.toJSONString(jsonObject);

    }

    private void setConfig(AccountInfo accountInfo, JSONObject jsonObject) {

        int cfg[] = {1, 3};

        List<FieldConfig> fieldConfigs = fieldConfigMapper.selectFieldConfigByType(accountInfo.getType(), cfg);

        for (FieldConfig fieldConfig : fieldConfigs) {
            String fieldName = fieldConfig.getFieldName();
            String fieldValue = fieldConfig.getFieldValue();
            List<String> fv = new ArrayList<>();
            if (StringUtils.isNotEmpty(fieldValue)) {
                String[] split = fieldValue.split(",");
                for (String s : split) {
                    if (accountInfo.getDes().contains(s)) {
                        fv.add(s);
                    }

                }

            }
            jsonObject.put(fieldName, JSONObject.toJSONString(fv));
        }

    }

    public static void main(String[] args) {

//
//        {
//            "game": "王者荣耀",
//                "price": "1800",
//                "cate_name": "安卓QQ",
//                "p_number": "252309",
//                "imgs":"https://youxihao.oss-cn-zhangjiakou.aliyuncs.com/5f7e912c7f7a7.jpg,https://youxihao.oss-cn-zhangjiakou.aliyuncs.com/5f7e912cb88a8.jpg,https://youxihao.oss-cn-zhangjiakou.aliyuncs.com/5f7e912cec9fc.jpg",
//                "description": "4S 11A 三星长门 三星秽土猿飞日斩 三星金角银角 三星鬼灯幻月 67个秽土波风水门碎片 52个猿飞日斩碎片",
//                "platform": "51youxihao",
//                "title": "WT【安卓抠】50英雄31皮肤安卓Q-50英雄31皮肤-夺萃鹰眼祸源150级，至尊宝，忍炎影，龙腾万里，死亡",
//                "is_indulge": 1,
//                "sign": "DBA10184D15A13385E29BE5DCD461ABC",
//        }
//

        String str = "gm28-安卓q-V7-108英雄-185皮肤-300五级铭文 7王者印记 未来机甲 幽冥火 253幸运值 " +
                "1内测 蔷薇恋人 零号赤焰 天狼绘梦者 天狼运算者 天狼溯光者 祈雪灵祝 逐梦之星 朱雀志 异界灵契 拒霜思 " +
                "孙行者 猪悟能 梁祝 地狱火 久胜战神 云霓雀翎 末日机甲女 无限星赏官 原初追逐者 黎明之约 原初探秘者 李小龙 " +
                "暗隐猎兽者 金属风暴 热力回旋 特工魅影 逐浪之夏 修罗 白龙吟 千年之狐 街头霸王 箭羽风息 星空之诺 鬼剑武藏 " +
                "朔望之晖 德古拉伯爵 银河之约 暗影游猎 云间偶戏 死神来了 冰冠公主 狂想玩偶喵 单词大作战 花好人间 狰 饕餮 " +
                "烛龙 重明 穷奇 御霄 御旌 御銮 朔风刀 混沌棋 疑决卦 醍醐杖 万华元夜 女仆咖啡 科学大爆炸 重装意志 奇遇舞章 " +
                "永昼 营地ID:459926613";
        String substring = str.substring(0, 150);
        System.out.println(substring);


        Map<String, Object> params = new TreeMap<>();
        params.put("game", "王者荣耀");
        params.put("price", new BigDecimal(1800));
        params.put("cate_name", "安卓QQ");
        params.put("p_number", 14356);
        params.put("imgs", "https://asdasda");
        params.put("description", "1fasdfadsfasd1");
        params.put("platform", "yud");
        params.put("title", "222fdsafasd");


        String cover = MapUntils.getCover(params);
        cover = cover + "key=57bl6a8rs9aosbwfvwq9f736dm1jto6i";
        String sign = DigestUtils.md5Hex(cover).toUpperCase();
        params.put("sign", sign);
//        String response = HttpUtils.sendPost(OutUrlConstant.LCADD, JSONObject.toJSONString(params),"application/json");
        String response = HttpUtils.sendPost("https://www.51youxihao.com/index.php?g=api&m=product&a=list_games", JSONObject.toJSONString(params), "application/json");
        System.out.println(response);
    }

}
